package priv.liaohaolong.fullstacktest;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import priv.liaohaolong.fullstacktest.filter.CaptchaValidationFilter;
import priv.liaohaolong.fullstacktest.security.AuthenticationFailureHandler;
import priv.liaohaolong.fullstacktest.security.AuthenticationSuccessHandler;
import priv.liaohaolong.fullstacktest.filter.JwtRequestFilter;

@Configuration
public class SecurityConfiguration {

    private final CaptchaValidationFilter captchaValidationFilter;

    private final JwtRequestFilter jwtRequestFilter;

    @Autowired
    public SecurityConfiguration(CaptchaValidationFilter captchaValidationFilter, JwtRequestFilter jwtRequestFilter) {
        this.captchaValidationFilter = captchaValidationFilter;
        this.jwtRequestFilter = jwtRequestFilter;
    }

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().requestMatchers(
                "/assets/**",
                "/favicon.ico"
        );
    }

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http, AuthenticationSuccessHandler successHandler, AuthenticationFailureHandler failureHandler) throws Exception {
        // 关闭 CSRF 防护，因为我们使用 JWT 进行认证，不需要 CSRF 防护
        http.csrf(AbstractHttpConfigurer::disable);

        // 配置跨域
        http.cors(configurer -> configurer.configure(http));

        // 配置登录接口
        http.formLogin(configurer -> configurer
                .loginPage("/login")
                .successHandler(successHandler)
                .failureHandler(failureHandler)
                .permitAll()
        );

        // 配置授权规则(包括Mapping接口和需要权限控制的静态资源)
        http.authorizeHttpRequests(registry -> registry
                // 放行静态资源
                // api 接口需要认证
                .requestMatchers("/api/**").authenticated()
                // 剩余接口放行
                .anyRequest().permitAll()
        );

        // 配置异常处理
        http.exceptionHandling(configurer -> configurer
                // 未登录（正常情况下应该跳转到登录页面，但是我们是前后端分离，所以返回 401，前端根据状态码跳转到登录页面）
                .authenticationEntryPoint((request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
        );

        // 禁用 session
        http.sessionManagement(configurer -> configurer
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        );

        // 添加过滤器
        http.addFilterBefore(captchaValidationFilter, UsernamePasswordAuthenticationFilter.class);
        http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
        return configuration.getAuthenticationManager();
    }

}
